﻿using _1._8._2015_AuthExample.Data.Models;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity.Migrations;

namespace _1._8._2015_AuthExample.Data
{
    public static class Seeder
    {
        public static void Seed(ApplicationDbContext db)
        {
            UserStore<ApplicationUser> userStore = new UserStore<ApplicationUser>(db);
            UserManager<ApplicationUser> userManager = new UserManager<ApplicationUser>(userStore);

            RoleStore<Role> roleStore = new RoleStore<Role>(db);
            RoleManager<Role> roleManager = new RoleManager<Role>(roleStore);

            if (!roleManager.RoleExists("General"))
            {
                var result = roleManager.Create(new Role
                {
                    Name = "General"
                });

                if (!result.Succeeded)
                {
                    string errorString = string.Empty;
                    result.Errors.ToList().ForEach(e => errorString += "| " + e);
                }
            }

            if (!roleManager.RoleExists("Admin"))
            {
                roleManager.Create(new Role
                {
                    Name = "Admin"
                });
            }

            ApplicationUser nick = userManager.FindByName("nick@codercamps.com");

            if (nick == null)
            {
                nick = new ApplicationUser
                {
                    Email = "nick@codercamps.com",
                    UserName = "nick@codercamps.com",
                    FirstName = "Nick",
                    LastName = "Brittain"                    
                };

                userManager.Create(nick, "123456");
                userManager.AddToRole(nick.Id, "Admin");

                nick = userManager.FindByName("nick@codercamps.com");
            }
            else
            {
                //Updates
                nick.Email = "nick@codercamps.com";
                if (!userManager.IsInRole(nick.Id, "Admin"))
                {
                    userManager.AddToRole(nick.Id, "Admin");
                }
            }

            db.Addresses.AddOrUpdate(a => a.Street, new Address
            {
                City = "Pearland",
                Street = "1212 Broadway Rd.",
                State = "TX",
                Zip = "77581",
                UserId = nick.Id
            });

            db.SaveChanges();
        }
    }
}
